<?php

namespace App\models\rbac;
use App\models\Base;
/**
* This is the model class for table "rbac_resource_uri".
*
* @property integer $id 
* @property integer $resource_id 
* @property string $uri 
* @property string $method 
*/
class ResourceUri extends Base
{

    // 自动时间戳对应的变量
    //const CREATED_AT = 'created_at';
    //const UPDATED_AT = 'updated_at';

    protected $primaryKey = 'id';

    // 是否需要自动时间戳
    //public $timestamps = false;

    // 时间的格式类型
    //protected $dateFormat = 'Y-m-d';

    //protected $connection = 'default';

    protected $table = 'rbac_resource_uri';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'resource_id','uri','method'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [

    ];

    public static function formatUri($uri,$resId){
        $uri = trim($uri);
        $uri = explode("\n",$uri) ;
        $rs = [] ;
        foreach ($uri as $u){
            $u = trim($u) ;
            if(!empty($u)){

                $u = explode('@',$u) ;
                $u = array_filter($u) ;
                $len = count($u);

                $data = ['resource_id' => $resId , 'uri' => trim($u[0]) , 'method' => ''] ;
                if($len > 1 && !empty($u[1])){
                    $data['method'] =  strtolower(trim($u[1])) ;
                }
                $rs[] = $data ;
            }
        }
        return $rs ;
    }

    public static function saveUris($uri,$resId){
        static::where('resource_id',$resId)->delete();
        $data = self::formatUri($uri,$resId) ;
        if(empty($data)){
            return ;
        }
        return static::insert($data) ;
    }
}
